import os
import cgi
import datetime 

from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

from google.appengine.api import users

#---------------------------------
#--- Database --------------------
#---------------------------------

class Entry(db.Model):
    author = db.UserProperty()
    title = db.StringProperty(multiline=False)
    tags = db.ListProperty(db.Category)
    category = db.Category("unfiled")
    folderKey = db.ReferenceProperty()
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)
    upvotes = db.IntegerProperty()
    downvotes = db.IntegerProperty()
    rating = db.Rating(0)

class Vote(db.Model):
    voter = db.UserProperty()
    entryKey = db.ReferenceProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    votetype = db.StringProperty() # should be 'up' or 'down'

class UserInfo(db.Model):
    admin = db.BooleanProperty()
    user = db.UserProperty(auto_current_user=True)
    votes = db.IntegerProperty(10) # stores the number of votes left
    lastFreeVoteOn = db.DateTimeProperty(auto_now_add=True) # they get one per day

class UserComment(db.Model):
    thread = None # db.ReferenceProperty()
    parentComment = db.ReferenceProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    content = db.StringProperty(multiline=True)
    upvotes = db.IntegerProperty()
    downvotes = db.IntegerProperty()
    rating = db.Rating(0)
    

#---------------------------------
#--- Pages -----------------------
#---------------------------------

class AdminPage(webapp.RequestHandler):
    def get(self):
        user=users.get_current_user()
        users_query = UserInfo.all().filter('user = ',user)
        userInfo=users_query.fetch(1)[0]
        #is user admin? If not, turn them back to main page
        #if not userInfo.admin:
        #    self.redirect('/')

        template_values = {
            'user':user,
            'admin':userInfo.admin
        }

        path = os.path.join(os.path.dirname(__file__), 'templates/admin.html')
        self.response.out.write(template.render(path, template_values))
        


class MainPage(webapp.RequestHandler):
    def get(self):
        entries_query = Entry.all().order('-date')
        entries = entries_query.fetch(10)

        entries_pack=[]
        for entry in entries:
            entries_pack.append( {'ago':humanize_timesince(entry.date), 'entry':entry} )
            
        votes=None
        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            user=users.get_current_user()
            url_linktext = 'Logout '+user.nickname()
            users_query = UserInfo.all().filter('user = ',user)
            userInfoList=users_query.fetch(1)
            if len(userInfoList)==1:
                userInfo=userInfoList[0]
                votes=userInfo.votes
            else:
                userInfo=UserInfo()
                userInfo.user=user
                userInfo.votes=10
                votes=userInfo.votes
                days_since_freevote=days_since(userInfo.lastFreeVoteOn)
                if days_since_freevote>0:
                    userInfo.lastFreeVoteOn=userInfo.votes+days_since_freevote
                    userInfo.date=datetime.datetime
                #TODO The next two lines must die in production.
                if user.nickname=='miketomaino':
                    userInfo.admin=True
                userInfo.put()
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'
            
               
        template_values = {
            'entries': entries_pack,
            'url': url,
            'url_linktext': url_linktext,
            'loggedin':False,
            'votes':votes
            }
        if users.get_current_user():
            template_values['loggedin']=True;

        path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
        self.response.out.write(template.render(path, template_values))

class UserPage(webapp.RequestHandler):
    def get(self):
        user=users.get_current_user()
        if user:
            entry_query=Entry.all().filter('user = ', user)
            entries=entry_query.fetch(10)
            template_values = {
                'user':user,
                'posts':entries
            } 
            path = os.path.join(os.path.dirname(__file__), 'templates/user.html')
            self.response.out.write(template.render(path, template_values))
        else:  
            self.redirect('/')

#---------------------------------
#--- Actions ---------------------
#---------------------------------

class PostEntry(webapp.RequestHandler):
    def post(self):
        if users.get_current_user():
            entry = Entry()
            entry.author = users.get_current_user()
            entry.content = self.request.get('content')
            entry.title = self.request.get('title')
            entry.upvotes = 0
            entry.put()
	self.redirect('/')

class Upvote(webapp.RequestHandler):
    def get(self):
        user=users.get_current_user()
        if user:
            key=self.request.get('key')
            greeting = db.get(key)
            greeting.upvotes+=1
            greeting.put()
            vote=Vote()
            vote.username=user
            vote.recordkey=key
            vote.votetype='up'
            users_query = UserInfo.all().filter('user = ',user)
            userInfoList=users_query.fetch(1)
            userInfo=userInfoList[0]
            userInfo.votes=userInfo.votes-1
            userInfo.put()


        self.redirect('/')


#---------------------------------
#--- Helpers ---------------------
#---------------------------------

def humanize_timesince(start_time):
    delta = datetime.datetime.now() - start_time

    plural = lambda x: 's' if x != 1 else ''

    num_years = delta.days / 365
    if (num_years > 0):
        return "%d year%s" % (num_years, plural(num_years))

    num_weeks = delta.days / 7
    if (num_weeks > 0):
        return "%d week%s" % (num_weeks, plural(num_weeks))

    if (delta.days > 0):
        return "%d day%s" % (delta.days, plural(delta.days))

    num_hours = delta.seconds / 3600
    if (num_hours > 0):
        return "%d hour%s" % (num_hours, plural(num_hours))

    num_minutes = delta.seconds / 60
    if (num_minutes > 0):
        return "%d minute%s" % (num_minutes, plural(num_minutes))

    return "a few seconds"

def days_since(start_time):
    delta = datetime.datetime.now() - start_time
    return delta.days 


#---------------------------------
#--- Start here! -----------------
#---------------------------------
application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/postEntry', PostEntry),
                                      ('/upvote', Upvote),
                                      ('/user', UserPage),
                                      ('/admin', AdminPage)
                                     ],debug=True)
                                     


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
